using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Models;
using System.IO;
using System.Collections;
using System.Web.Security;
using MVCWeb.Models.ViewData;
using System.Configuration;

namespace MVCWeb.Controllers
{
    public class DocController : BaseController
    {
        //
        // GET: /Doc/
        [Authorize(Roles = "Administrators")]
        public ActionResult Index(int? communityId)
        {
            var Docs = from x in dc.Docs
                       where x.DocCategoryId != 1
                       group x by x.DocCategory into r
                       select new { Category = r.Key, Docs = r };

            IList<DocCategory> docCategories = new List<DocCategory>();

            foreach (var item in Docs)
            {
                DocCategory category = new DocCategory();
                category.Category = Convert.ToString(item.Category.Category);
                category.DocCategoryId = item.Category.DocCategoryId;
                category.Docs = item.Category.Docs;
                docCategories.Add(category);
            }



            return View(docCategories.ToList<DocCategory>());
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult IndexOfLegislative()
        {

            var Docs = from x in dc.Docs
                       where x.DocCategoryId == 1
                       group x by x.DocCategory into r
                       select new { Category = r.Key, Docs = r };

            IList<DocCategory> docCategories = new List<DocCategory>();
            foreach (var item in Docs)
            {
                DocCategory category = new DocCategory();
                category.Category = Convert.ToString(item.Category.Category);
                category.DocCategoryId = item.Category.DocCategoryId;
                category.Docs = item.Category.Docs;
                docCategories.Add(category);
            }

            return View(docCategories.ToList<DocCategory>());
        }

        [Authorize]
        public ActionResult Details(int id)
        {
            Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);
            return View(doc);
        }

        [Authorize]
        public ActionResult Download(string path)
        {
            return RedirectToAction("Index");
        }

        //
        // GET: /Doc/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            DocumentNewViewData data = new DocumentNewViewData();
            IList<DocCategory> finalCategories = new List<DocCategory>();

            IList<DocCategory> allCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
            IList<DocCategory> topCategories = allCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false)).OrderBy(c => c.Category).ToList<DocCategory>();

            foreach (var item in topCategories)
            {
                finalCategories.Add(item);
                IList<DocCategory> subCategories = allCategories.Where(c => c.ParentDocCategoryId == item.DocCategoryId).OrderBy(c => c.Category).ToList<DocCategory>();
                foreach (var subitem in subCategories)
                {
                    subitem.Category = "-- " + subitem.Category;
                    finalCategories.Add(subitem);
                }
            }

            data.Categories = finalCategories;// dc.DocCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false) && c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
            data.Communities = dc.Communities.OrderBy(c => c.Name).ToList<Community>();
            data.Document = new Doc();
            return View(data);
        }


        //
        // GET: /Doc/CreateLegislativeDoc
        [Authorize(Roles = "Administrators")]
        public ActionResult CreateLegislativeDoc()
        {
            DocumentNewViewData data = new DocumentNewViewData();
            data.Document = new Doc();
            data.Categories = this.dc.DocCategories.OrderBy(c => c.Category).ToList<DocCategory>();
            return View(data);
        }

        //
        // POST: /Doc/CreateLegislativeDoc
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult CreateLegislativeDoc(Doc documentToCreate)
        {
            try
            {
                int companyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                int catId = 1;
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    //uploads\{companyid}\Category{Categoryid}\doc
                    string savePath = @"Uploads\" + companyId + "\\" + catId + "\\Doc\\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName) + file_append.ToString() + extension;
                    }

                    savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);

                    documentToCreate.Size = hpf.ContentLength;
                    documentToCreate.FullPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    documentToCreate.URLLink = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);

                }

                documentToCreate.DocCategoryId = 1; // Fixed category for Legislative Updates;
                documentToCreate.ModifiedDate = DateTime.Now;
                this.dc.Docs.InsertOnSubmit(documentToCreate);
                this.dc.SubmitChanges();

                return RedirectToAction("IndexOfLegislative");
            }
            catch
            {
                FileInfo oldFile = new FileInfo(documentToCreate.FullPath);
                if (oldFile.Exists)
                {
                    oldFile.Delete();
                }
                return RedirectToAction("IndexOfLegislative");
            }

        }

        //
        // GET: /Doc/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult EditLegislativeDoc(int? id)
        {
            DocumentNewViewData data = new DocumentNewViewData();
            data.Document = dc.Docs.First<Doc>(x => x.DocId == id);
            data.Categories = this.dc.DocCategories.OrderBy(c => c.Category).ToList<DocCategory>();
            return View(data);
        }

        //
        // POST: /Doc/Edit/5

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult EditLegislativeDoc(int id, FormCollection collection)
        {
            try
            {
                int companyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                int catId = 1;

                Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);

                foreach (string file in Request.Files)
                {
                    FileInfo oldFile = new FileInfo(doc.FullPath);
                    if (oldFile.Exists)
                    {
                        oldFile.Delete();
                    }

                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Uploads\" + companyId + "\\" + catId + "\\Doc\\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                         + file_append.ToString()
                                         + extension;
                    }
                    savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);

                    doc.Size = hpf.ContentLength;
                    doc.FullPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    doc.URLLink = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);

                }
                doc.Desc = collection["Desc"];
                doc.ModifiedDate = DateTime.Now;
                doc.DocCategoryId = catId;
                UpdateModel<Doc>(doc);
                dc.SubmitChanges();
                return RedirectToAction("IndexOfLegislative");
            }
            catch
            {
                return RedirectToAction("IndexOfLegislative");
            }
        }

        //
        // POST: /Doc/Create

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Create(Doc doc, FormCollection collection)
        {
            try
            {
                int companyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                int communityId = Int32.Parse(collection["CommunityId"]);

                int categoryId = 0;
                if (collection["NewCategoryName"].Length > 0 && collection["NewSubCategoryName"].Length > 0)
                {
                    DocCategory cat = new DocCategory();
                    cat.Category = collection["NewCategoryName"];
                    cat.ParentDocCategoryId = 0;
                    cat.Desc = "";
                    dc.DocCategories.InsertOnSubmit(cat);
                    dc.SubmitChanges();

                    DocCategory subcat = new DocCategory();
                    subcat.Category = collection["NewSubCategoryName"];
                    subcat.ParentDocCategoryId = cat.DocCategoryId;
                    subcat.Desc = "";
                    dc.DocCategories.InsertOnSubmit(subcat);
                    dc.SubmitChanges();

                    categoryId = subcat.DocCategoryId;
                }
                else if (collection["NewCategoryName"].Length == 0 && collection["NewSubCategoryName"].Length > 0)
                {
                    DocCategory docCat = this.dc.DocCategories.Single(c => c.DocCategoryId == Int32.Parse(collection["DocCategoryId"]));
                    if (docCat.ParentDocCategoryId != 0)
                    {
                        ModelState.AddModelError("", "Category must be selected as root category");
                    }
                    else
                    {
                        DocCategory subcat = new DocCategory();
                        subcat.Category = collection["NewSubCategoryName"];
                        subcat.ParentDocCategoryId = Int32.Parse(collection["DocCategoryId"]);
                        subcat.Desc = "";
                        dc.DocCategories.InsertOnSubmit(subcat);
                        dc.SubmitChanges();

                        categoryId = subcat.DocCategoryId;
                    }
                }
                else if (collection["NewCategoryName"].Length == 0 && collection["NewSubCategoryName"].Length == 0)
                {
                    DocCategory docCat = this.dc.DocCategories.Single(c => c.DocCategoryId == Int32.Parse(collection["DocCategoryId"]));
                    if (docCat.ParentDocCategoryId == 0)
                    {
                        ModelState.AddModelError("", "Category must be selected as sub category");
                    }
                    else
                    {
                        categoryId = Int32.Parse(collection["DocCategoryId"]);
                    }
                }

                if (ModelState.IsValid)
                {

                    doc.DocCategoryId = categoryId;

                    foreach (string file in Request.Files)
                    {
                        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                        if (hpf.ContentLength == 0)
                            continue;


                        //uploads\{companyid}\{communityid}\{categoryid}\doc
                        string savePath = @"Uploads\" + companyId + "\\" + communityId + "\\" + categoryId + "\\Doc\\";

                        string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                        if (!Directory.Exists(physicPath))
                        {
                            Directory.CreateDirectory(physicPath);
                        }

                        string sFilename = Path.GetFileName(hpf.FileName);
                        string savedFileName = Path.Combine(physicPath, sFilename);

                        string extension = Path.GetExtension(hpf.FileName).ToLower();

                        int file_append = 0;
                        while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                        {
                            file_append++;
                            sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                             + file_append.ToString()
                                             + extension;
                        }

                        savedFileName = Path.Combine(physicPath, sFilename);

                        hpf.SaveAs(savedFileName);

                        doc.Size = hpf.ContentLength;
                        doc.FullPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                        doc.URLLink = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);

                    }

                    doc.ModifiedDate = DateTime.Now;
                    dc.Docs.InsertOnSubmit(doc);
                    dc.SubmitChanges();

                    CommunityDoc communityDoc = new CommunityDoc();
                    communityDoc.DocId = doc.DocId;

                    // Get community by login user.
                    //MembershipUser membershipUser = Membership.GetUser();
                    //Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                    //User user = dc.Users.Where<User>(u => u.MembershipId == membershipId).First<User>();
                    //Community community = user.Communities.Where<Community>(c => c.UserId == user.UserId).First<Community>();
                    //int communityId = community.CommunityId;

                    communityDoc.CommunityId = communityId;
                    communityDoc.MeetingId = 1;
                    dc.CommunityDocs.InsertOnSubmit(communityDoc);
                    dc.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    DocumentNewViewData data = new DocumentNewViewData();
                    IList<DocCategory> finalCategories = new List<DocCategory>();

                    IList<DocCategory> allCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
                    IList<DocCategory> topCategories = allCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false)).OrderBy(c => c.Category).ToList<DocCategory>();

                    foreach (var item in topCategories)
                    {
                        finalCategories.Add(item);
                        IList<DocCategory> subCategories = allCategories.Where(c => c.ParentDocCategoryId == item.DocCategoryId).OrderBy(c => c.Category).ToList<DocCategory>();
                        foreach (var subitem in subCategories)
                        {
                            subitem.Category = "-- " + subitem.Category;
                            finalCategories.Add(subitem);
                        }
                    }

                    data.Categories = finalCategories;// dc.DocCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false) && c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
                    data.Communities = dc.Communities.OrderBy(c => c.Name).ToList<Community>();
                    data.Document = new Doc();
                    return View(data);
                }
            }
            catch
            {
                FileInfo oldFile = new FileInfo(doc.FullPath);
                if (oldFile.Exists)
                {
                    oldFile.Delete();
                }
                return RedirectToAction("Index");
            }
        }

        //
        // GET: /Doc/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int? id)
        {
            Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);
            var docCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).ToList<DocCategory>();


            IList<DocCategory> finalCategories = new List<DocCategory>();

            IList<DocCategory> allCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
            IList<DocCategory> topCategories = allCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false)).OrderBy(c => c.Category).ToList<DocCategory>();

            foreach (var item in topCategories)
            {
                finalCategories.Add(item);
                IList<DocCategory> subCategories = allCategories.Where(c => c.ParentDocCategoryId == item.DocCategoryId).OrderBy(c => c.Category).ToList<DocCategory>();
                foreach (var subitem in subCategories)
                {
                    subitem.Category = "-- " + subitem.Category;
                    finalCategories.Add(subitem);
                }
            }
            ViewData["DocCategoryId"] = new SelectList(finalCategories, "DocCategoryID", "Category", doc.DocCategoryId);

            CommunityDoc communityDoc = dc.CommunityDocs.Single<CommunityDoc>(x => x.DocId == doc.DocId);

            var communities = dc.Communities.OrderBy(c => c.Name).ToList<Community>();
            ViewData["CommunityId"] = new SelectList(communities, "CommunityId", "Name", communityDoc.CommunityId);
            return View(doc);
        }

        //
        // POST: /Doc/Edit/5

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                int companyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                int communityId = Convert.ToInt32(collection["CommunityId"]);
                int categoryId = Convert.ToInt32(collection["DocCategoryId"]);

                DocCategory docCat = this.dc.DocCategories.Single(c => c.DocCategoryId == Int32.Parse(collection["DocCategoryId"]));
                if (docCat.ParentDocCategoryId == 0)
                {
                    ModelState.AddModelError("", "Category must be selected as sub category");
                }

                if (ModelState.IsValid)
                {
                    Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);

                    foreach (string file in Request.Files)
                    {
                        FileInfo oldFile = new FileInfo(doc.FullPath);
                        if (oldFile.Exists)
                        {
                            oldFile.Delete();
                        }

                        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                        if (hpf.ContentLength == 0)
                            continue;

                        string savePath = @"Uploads\" + companyId + "\\" + communityId + "\\" + categoryId + "\\Doc\\";

                        string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                        if (!Directory.Exists(physicPath))
                        {
                            Directory.CreateDirectory(physicPath);
                        }

                        string sFilename = Path.GetFileName(hpf.FileName);
                        string savedFileName = Path.Combine(physicPath, sFilename);

                        string extension = Path.GetExtension(hpf.FileName).ToLower();

                        int file_append = 0;
                        while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                        {
                            file_append++;
                            sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                             + file_append.ToString()
                                             + extension;
                        }
                        savedFileName = Path.Combine(physicPath, sFilename);

                        hpf.SaveAs(savedFileName);

                        doc.Size = hpf.ContentLength;
                        doc.FullPath = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                        doc.URLLink = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);

                    }
                    doc.Desc = collection["Desc"];
                    doc.DocCategoryId = categoryId;
                    UpdateModel<Doc>(doc);
                    dc.SubmitChanges();

                    CommunityDoc communityDoc = dc.CommunityDocs.Single<CommunityDoc>(d => d.DocId == doc.DocId);
                    communityDoc.CommunityId = communityId;
                    communityDoc.MeetingId = 1;

                    dc.SubmitChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);
                    var docCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).ToList<DocCategory>();


                    IList<DocCategory> finalCategories = new List<DocCategory>();

                    IList<DocCategory> allCategories = dc.DocCategories.Where(c => c.DocCategoryId != 1).OrderBy(c => c.Category).ToList<DocCategory>();
                    IList<DocCategory> topCategories = allCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false)).OrderBy(c => c.Category).ToList<DocCategory>();

                    foreach (var item in topCategories)
                    {
                        finalCategories.Add(item);
                        IList<DocCategory> subCategories = allCategories.Where(c => c.ParentDocCategoryId == item.DocCategoryId).OrderBy(c => c.Category).ToList<DocCategory>();
                        foreach (var subitem in subCategories)
                        {
                            subitem.Category = "-- " + subitem.Category;
                            finalCategories.Add(subitem);
                        }
                    }
                    ViewData["DocCategoryId"] = new SelectList(finalCategories, "DocCategoryID", "Category", doc.DocCategoryId);

                    CommunityDoc communityDoc = dc.CommunityDocs.Single<CommunityDoc>(x => x.DocId == doc.DocId);

                    var communities = dc.Communities.OrderBy(c => c.Name).ToList<Community>();
                    ViewData["CommunityId"] = new SelectList(communities, "CommunityId", "Name", communityDoc.CommunityId);
                    return View(doc);
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            try
            {
                Doc doc = dc.Docs.First<Doc>(x => x.DocId == id);

                FileInfo oldFile = new FileInfo(doc.FullPath);
                if (oldFile.Exists)
                {
                    oldFile.Delete();
                }
                dc.Docs.DeleteOnSubmit(doc);
                dc.SubmitChanges();
                return RedirectToAction("List", "Community");
            }
            catch
            {
                return RedirectToAction("List", "Community");
            }
        }
    }
}
